package com.abing.chatRoom.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.abing.chatRoom.model.domain.User;
import com.abing.chatRoom.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class PreCacheJob {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    //重点用户
    private List<Long> mainUserList = Arrays.asList(1L);
    // 每天执行，预热推荐用户
    @Scheduled(cron = "0 12 1 * * *")   //自己设置时间测试
    public void doCacheRecommerUser(){

        RLock rLock = redissonClient.getLock("abing:precachejob:docache:lock");
        try {
            if(rLock.tryLock(0,-1,TimeUnit.MILLISECONDS)){
            long pageNum=1,pageSize=8;
            ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
            String redisKey = String.format("abing:user:recommend:%s", mainUserList);
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            Page<User> userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
            //写缓存
            try {
                valueOperations.set(redisKey,userPage,30000, TimeUnit.MILLISECONDS);
            }catch (Exception e){
                log.error("redis set key error",e);
            }
        }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
        } finally {
            //只能释放自己的锁
            if(rLock.isHeldByCurrentThread()){
                System.out.println("unLock: " + Thread.currentThread().getId());
                rLock.unlock();
            }

        }


    }}
